package net.jsoft.platform.oauth2.service.impl.github;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import net.jsoft.platform.core.util.http.HttpUtils;
import net.jsoft.platform.oauth2.service.IThirdPartyLoginService;
import net.jsoft.platform.oauth2.util.ThirdPartyConstant;
import net.sf.json.JSONObject;

@Service("githubService")
public class GithubLoginSeriviceImpl implements IThirdPartyLoginService
{
    @Autowired
    private ThirdPartyConstant tpc;

    @Override
    public String getUser(String code)
    {
        String id = null;
        Map<String, String> map = new HashMap<String, String>();
        map.put("client_id", tpc.getGithubClientId());
        map.put("client_secret", tpc.getGithubClientSecret());
        map.put("code", code);

        String result = HttpUtils.get(tpc.getGithubAccessTokenUri(), map);
        if (result.indexOf("access_token") > -1)
        {
            String accessToken = result.split("&")[0];

            String s = HttpUtils.get(tpc.getGithubUserInfoUri() + "?" + accessToken);
            JSONObject obj = JSONObject.fromObject(s);
            id = obj.get("id") + "";

        }
        return id;
    }

}
